<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Title</title>
</head>
<body>
	<button>发送请求1</button>
	<button>发送请求2</button>
	<div id="app"></div>
</body>
<script>
	const btns = document.querySelectorAll("button");
	function ajax(config={}){
		let {url,method="get",success,params={},data} = config;
		let paramsUrl = Object.keys(params).map(key=>key+"="+params[key]).join("&");
		if(paramsUrl) url+="?"+paramsUrl;
		const xhr = new XMLHttpRequest();
		xhr.open(method,url);
		if(method==="post" && data){
			// 判断data是否为对象
			if(typeof data === "object"){
				xhr.setRequestHeader("Content-Type","application/json");
				xhr.send(JSON.stringify(data));
			}else{
				xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
				xhr.send(data);
			}
			xhr.send();
		}else{
			xhr.send();
		}
		
		xhr.onload = function(){
			success(xhr.response);
		};
	}
	ajax.get = function(url,config){
		this({
			url,
			...config
		})
	}
	ajax.post = function(url,data,config){
		this({
			url,
			method:"post",
			data,
			...config
		})
	}
	btns[0].onclick = function(){
		ajax.get("/info",{
			params:{
				a:1,
				b:2,
				c:3
			},
			success(res){
				console.log(res);
			}
		})
	}
	btns[1].onclick = function(){
		// 第一个参数是请求地址，第二个参数是请求体，第三个参数是配置信息
		ajax.post("/sum",{userName:"zhangsan",age:12},{
			params:{
				a:1,
				b:2,
				c:100
			},
			success(res){
				alert(res);
			}
		})
	}
</script>
</html>